#pragma once

#include <mutex>
#include "Util.hpp"

namespace cloud
{
#define CONFIG_FILE "./Cloud.conf"

    // 设计成单例模式
    class Config
    {
    private:
        Config()
        {
            bool ret = ReadConfigFile();
        }
        Config(const Config &conf) = delete;

        static std::mutex mtx_;
        static Config *instance_;

    private:
        int hot_time_;
        int server_port_;
        std::string server_ip_;
        std::string download_prefix_;
        std::string packfile_suffix_;
        std::string pack_dir_;
        std::string back_dir_;
        std::string back_file_data_;

    private:
        // 读取配置文件
        bool ReadConfigFile()
        {
            FileUtil fu(CONFIG_FILE);
            std::string content;
            if (!fu.GetContent(&content))
            {
                std::cout << "read Config file failed !" << std::endl;
                return false;
            }

            Json::Value root;
            if (!JsonUtil::UnSerialize(content, &root))
            {
                std::cout << "read config file failed !" << std::endl;
                return false;
            }
            hot_time_ = root["hot_time"].asInt();
            server_port_ = root["server_port"].asInt();
            server_ip_ = root["server_ip"].asString();
            download_prefix_ = root["download_prefix"].asString();
            packfile_suffix_ = root["packfile_suffix"].asString();
            pack_dir_ = root["pack_dir"].asString();
            back_dir_ = root["back_dir"].asString();
            back_file_data_ = root["back_file_data"].asString();
            return true;
        }

    public:
        static Config *GetInstance()
        {
            if (instance_ == nullptr)
            {
                mtx_.lock();
                if (instance_ == nullptr)
                {
                    instance_ = new Config();
                }
                mtx_.unlock();
            }
            return instance_;
        }

        int GetHotTime()
        {
            return hot_time_;
        }

        int GetServerPort()
        {
            return server_port_;
        }

        std::string GetServerIp()
        {
            return server_ip_;
        }

        std::string GetDownloadPrefix()
        {
            return download_prefix_;
        }

        std::string GetPackFileSuffix()
        {
            return packfile_suffix_;
        }

        std::string GetPackDir()
        {
            return pack_dir_;
        }

        std::string GetBackDir()
        {
            return back_dir_;
        }

        std::string GetBackFileData()
        {
            return back_file_data_;
        }
    };

    Config *Config::instance_ = nullptr;
    std::mutex Config::mtx_;
}
